<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { onMounted } from 'vue'
import { baseURL } from '@/utils/request'
import { io, type Socket } from 'socket.io-client'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { onUnmounted } from 'vue'
import type { Message, TimeMessages } from '@/types/room'
import { ref } from 'vue'
// import { MsgType } from '@/emuns'
import { MsgType, OrderType } from '@/enums'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { nextTick } from 'vue'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import { provide } from 'vue'

const route = useRoute()
const store = useUserStore()

const list = ref<Message[]>([])
const initialMsg = ref(true)
let socket: Socket
onMounted(async () => {
  // 建立连接
  socket = io(baseURL, {
    auth: {
      token: 'Bearer ' + store.user?.token
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 监听连接事件
  socket.on('connect', () => {
    console.log('连接成功')
    list.value = []
  })
  socket.on('error', (error) => {
    console.log('连接失败', error)
  })
  socket.on('disconnect', () => {
    console.log('连接断开')
  })
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    const msgList: Message[] = []
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime
      msgList.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime
      })
      msgList.push(...item.items)
    })
    list.value.unshift(...msgList)
    console.log(list)
    loading.value = false

    if (!data.length) {
      return showToast('没有聊天记录了')
    }
    const firstDom = document.querySelector('.msg')
    nextTick(() => {
      if (initialMsg.value) {
        // 消息已读
        socket.emit('updateMsgStatus', msgList[msgList.length - 1].id)
        window.scrollTo(0, document.body.scrollHeight)
        setTimeout(() => {
          initialMsg.value = false
        }, 300)
      } else {
        firstDom?.scrollIntoView()
        window.scrollBy(0, -150)
      }
    })
  })
})
onUnmounted(() => {
  socket.close()
})

// 订单详情
const consult = ref<ConsultOrderItem>()
provide('consult', consult)
const getConsult = async () => {
  const { data } = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = data
}
onMounted(() => {
  getConsult()
  socket.on('statusChange', getConsult)
  socket.on('receiveChatMsg', async (event) => {
    list.value.push(event)
    await nextTick()
    socket.emit('updateMsgStatus', event.id)
    setTimeout(() => {
      window.scrollTo(0, document.body.scrollHeight)
    }, 500)
  })
})
// 发送文字
const sendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: text }
  })
}
// 发送图片
const sendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img }
  })
}
// 刷新聊天记录
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const loading = ref(false)
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

// 更新评价
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list" />
    </van-pull-refresh>
    <room-action
      @send-image="sendImage"
      @send-text="sendText"
      :disabled="consult?.status !== OrderType.ConsultChat"
    />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
